package com.meme.editor.gui.sprite2d;

import java.awt.Graphics;
import java.awt.SystemColor;
import java.awt.event.MouseWheelListener;

import javax.swing.JPanel;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

import com.meme.editor.EntityObject;
import com.meme.editor.model.sprite2d.ModuleImage;

import com.meme.editor.event.EntityChangedEvent;
import com.meme.editor.event.EntityObjectListener;

public class ModuleImageView extends JPanel implements EntityObjectListener, AncestorListener, MouseWheelListener
{
	ModuleImage mModuleImage;
	
	static final int MaxScale = 8;
	static final int MinScale = 1;
	static final int DefaultScale = 1;
	
	int mScale = DefaultScale;
	
	public ModuleImageView (ModuleImage moduleImage)
	{
		mModuleImage = moduleImage;
		
		addAncestorListener (this);
		addMouseWheelListener (this);
	}
	
	@Override
	public void paintComponent (Graphics g)
	{
		int width = getWidth ();
		int height = getHeight ();
		g.setColor (SystemColor.window);
		g.fillRect (0, 0, width, height);
		
		if ( mModuleImage.isValid() )
		{
			int imgWidth = mModuleImage.getWidth() * mScale;
			int imgHeight = mModuleImage.getHeight() * mScale;

			g.drawImage(mModuleImage.getImage(), (width - imgWidth) / 2, (height - imgHeight) / 2, imgWidth, imgHeight, this);
			//mModuleImage.render(g);
		}
	}
	
	// PropertyManagerListener
	@Override 
	public void notifyEntityChanged (EntityChangedEvent event)
	{ 
		repaint ();
	}
	
	
	@Override
	public void ancestorAdded(AncestorEvent event) 
	{
		mModuleImage.addEntityObjectListener (this);		
	}

	@Override
	public void ancestorRemoved(AncestorEvent event)  
	{
		mModuleImage.removeEntityObjectListener (this);	
	}
	
	@Override
	public void ancestorMoved(AncestorEvent event) 
	{
		
	}
	
	
//--------------------------------------------------------------------------
// as a MouseWheelListener
//--------------------------------------------------------------------------

	  // Method descriptor #8 (Ljava/awt/event/MouseWheelEvent;)V
	  public void mouseWheelMoved(java.awt.event.MouseWheelEvent event)
	  {
		  float scale = (float)mScale + (float) event.getWheelRotation ();
		  
		  if ( scale < MinScale)
			  scale = MinScale;
		  if (scale > MaxScale)
			  scale = MaxScale;
		  
		  mScale = (int) scale;

		  repaint ();
	  }
		  	
}
